
// 千分符转换
function thousandSeparator(amount, fixed = 2, isRoundingOff = true) {
  let num = ''
  if (Number.isNaN(Number.parseFloat(amount))) {
    num = ''
    return
  } 
  else {
    num = Number.parseFloat(amount) + ''
  }
  let intNum = num
  let floatNum = supplement(fixed)
  if (num.indexOf(',') !== -1) {
    num = num.split(',').join('')
  }
  if (num.indexOf('.') !== -1) {
    const loadAtmArr = num.split('.')
    intNum = loadAtmArr[0]
    if (loadAtmArr[1].length > fixed) {
      if (isRoundingOff) {
        const getRoundingArr = roundingOff(loadAtmArr[1], fixed)
        if (getRoundingArr.length > fixed) {
          intNum = (Number.parseInt(intNum) + 1) + ''
          getRoundingArr.shift()
        }
        floatNum = getRoundingArr.join('')
      } else {
        floatNum = loadAtmArr[1].substring(0, fixed)
      }
    } else if (loadAtmArr[1].length < fixed) {
      const add = fixed - loadAtmArr[1].length
      floatNum = loadAtmArr[1] + supplement(add)
    } else {
      floatNum = loadAtmArr[1]
    }
  }
  if (intNum.length >= 4) {
    const intNumArr = intNum.split('')
    for (let index = intNumArr.length - 3; index > 0; index -= 3) {
      intNumArr.splice(index, 0, ',')
    }
    intNum = intNumArr.join('')
  }
  return (intNum + '.' + floatNum)
}

//  补零
function supplement(limit) {
  let supplementZero = ''
  for (let index = 0; index < limit; index++) {
    supplementZero += '0'
  }
  return supplementZero
}

// 防抖
function debounce(fn, delay) {
  let timer = null
  return function() {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay);
  }
}

// 节流
function throttle(fn, delay) {
  let valid = true
  return function () {
    if (valid) {
      setTimeout(() => {
        fn.apply(this, arguments)
        valid = true
      }, delay)
      valid = false
    } else {
      return false
    }
  }
}

// 获取缓存
function getItem(key) {
	let returnVal = uni.getStorageSync(key)
	if (returnVal) {
		returnVal = JSON.parse(uni.getStorageSync(key))
	}
	return returnVal
}

// 设置缓存
function setItem(key, value) {
	uni.setStorageSync(key, JSON.stringify(value))
}



// 深拷贝
function deepClone(obj) {
	let newObj = Array.isArray(obj) ? [] : {}
	if (obj && typeof obj === 'object') {
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] && typeof obj[key] === 'object') {
					newObj[key] = deepClone(obj[key])
				} else {
					newObj[key] = obj[key]
				}
			}
		}
	}
	
	return newObj
}

export default {
	thousandSeparator,
	supplement,
	deepClone,
	throttle,
	getItem,
	setItem
}